﻿using System;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Ink;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Xml.Linq;
using System.Linq;
using System.Threading;
using System.ComponentModel;
using System.Windows.Navigation;
using Microsoft.Phone.Controls;
using System.Net.NetworkInformation;
using System.Text.RegularExpressions;
using System.IO;

namespace Mad.Nug.Rss
{
    public class RssReader : ViewModel.Base.VMBase
    {
        PhoneApplicationFrame mainFrame = (App.Current.RootVisual as PhoneApplicationFrame);
        #region Public properties
        /// <summary>
        /// The string source to connect.
        /// </summary>
        public string rssSource { get; set; }
        private Collection<RssItem> _items;
        public Collection<RssItem> Items
        {
            get
            {
                return _items;
            }
            set
            {
                _items = value;
            }
        }

        private RssItem _selectedItem;
        public RssItem SelectedItem
        {
            get
            {
                return _selectedItem;
            }
            set
            {
                if (value != null)
                {
                    _selectedItem = value;
                    (App.Current as App).selectedItem = SelectedItem;
                    (App.Current as App).selectedSection = SectionName;
                    mainFrame = (App.Current.RootVisual as PhoneApplicationFrame);
                    mainFrame.Source = new Uri("/View/ViewItem.xaml", UriKind.Relative);
                    //(mainFrame.Content as MainPage).ExitPage.Completed += new EventHandler(ExitPage_Completed);
                    //(mainFrame.Content as MainPage).ExitPage.Begin();
                }
            }
        }

        void ExitPage_Completed(object sender, EventArgs e)
        {
            mainFrame.Source = new Uri("/View/.xaml", UriKind.Relative);
        }

        private Collection<RssItem> ThreadSafeItems;
        private Stream ThreadSafeStream;

        HttpWebRequest rssRequest;

        private Visibility _progress = Visibility.Visible;
        public Visibility Progress
        {
            get
            {
                return _progress;
            }
            set
            {
                _progress = value;
                NotifyPropertyChanged("Progress");
            }
        }

        private Visibility _progressLoad = Visibility.Visible;
        public Visibility ProgressLoad
        {
            get
            {
                return _progressLoad;
            }
            set
            {
                _progressLoad = value;
                NotifyPropertyChanged("ProgressLoad");
            }
        }

        private string SectionName = "";
        #endregion

        #region Constructor
        public RssReader()
        {
            Progress = Visibility.Visible;
        }

        public RssReader(string _section)
        {
            SectionName = _section;
            Progress = Visibility.Visible;
        }
        #endregion

        #region public methods

        public void LoadRssItems()
        {
            if (System.ComponentModel.DesignerProperties.IsInDesignTool == false)
            {
                try
                {
                    mainFrame = (App.Current.RootVisual as PhoneApplicationFrame);
                    rssRequest = HttpWebRequest.CreateHttp(rssSource);
                    rssRequest.BeginGetResponse(new AsyncCallback(completed), null);
                }
                catch (Exception)
                {
                    MessageBox.Show("No ha sido posible conectar con el servidor.");
                }
            }
        }

        void completed(IAsyncResult result)
        {
            try
            {
                WebResponse response = rssRequest.EndGetResponse(result);

                BackgroundWorker worker = new BackgroundWorker();
                worker.DoWork += new DoWorkEventHandler(worker_DoWork);
                worker.RunWorkerCompleted += new RunWorkerCompletedEventHandler(worker_RunWorkerCompleted);
                ThreadSafeStream = response.GetResponseStream();
                worker.RunWorkerAsync();
            }
            catch (Exception)
            {
            }
        }

        void worker_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
        {
            Items = ThreadSafeItems;
            NotifyPropertyChanged("Items");
            Progress = Visibility.Collapsed;
        }

        void worker_DoWork(object sender, DoWorkEventArgs e)
        {
            XDocument Documento;
            using (StreamReader reader = new StreamReader(ThreadSafeStream))
            {
                Documento = XDocument.Parse(reader.ReadToEnd());
            }
            XNamespace dc = @"http://purl.org/dc/elements/1.1/";
            XNamespace content = @"http://purl.org/rss/1.0/modules/content/";
            XNamespace wfw = @"http://wellformedweb.org/CommentAPI/";
            //Rss Content
            ThreadSafeItems = new Collection<RssItem>(
                    (from ItemElement in Documento.Descendants("item")
                     select new RssItem
                     {
                         Title = ItemElement.Element("title").Value.Substring(ItemElement.Element("title").Value.ToString().LastIndexOf("]")+1).Trim(),
                         Text = ItemElement.Element("description").Value,
                         Description = ItemElement.Element(content + "encoded").Value,
                         Image = ItemElement.Element("enclosure") == null ? "../ApplicationIcon.png" : ItemElement.Element("enclosure").Attribute("url").Value.Contains(".gif") ? "../ApplicationIcon.png" : ItemElement.Element("enclosure").Attribute("url").Value,
                         Date = ItemElement.Element("pubDate") == null ? "" : ItemElement.Element("pubDate").Value.Substring(0, ItemElement.Element("pubDate").Value.Length - 6),
                         Url = new Uri(ItemElement.Element("link").Value),
                         CommentsUrl = ItemElement.Element(wfw + "commentRss") != null ? new Uri(ItemElement.Element(wfw + "commentRss").Value) : new Uri(@"http://madriddotnet.worpress.com"),
                         Author = ItemElement.Element(dc + "creator").Value
                     }).ToList());

            if (mainFrame != null)
                mainFrame.Dispatcher.BeginInvoke((Action)delegate()
                {
                    ProgressLoad = Visibility.Collapsed;
                });
        }

        void UpdateProgressLoad()
        {
            ProgressLoad = Visibility.Collapsed;
        }
        #endregion
    }
}
